<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/ice.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/ice.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":3,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="1.什么是重构？在不改变软件可观察行为的前提下，使用一些重构的手法，提高代码可读性。 换句话说，在保持软件可用的前提下，修改代码使得更加容易被理解。">
<meta property="og:type" content="article">
<meta property="og:title" content="重构的原则">
<meta property="og:url" content="http://yoursite.com/2020/05/30/%E9%87%8D%E6%9E%84--%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/Chapter%202%20%E9%87%8D%E6%9E%84%E7%9A%84%E5%8E%9F%E5%88%99/index.html">
<meta property="og:site_name" content="严冰的博客">
<meta property="og:description" content="1.什么是重构？在不改变软件可观察行为的前提下，使用一些重构的手法，提高代码可读性。 换句话说，在保持软件可用的前提下，修改代码使得更加容易被理解。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-05-30T12:50:49.000Z">
<meta property="article:modified_time" content="2020-06-18T00:01:07.887Z">
<meta property="article:author" content="yanbing">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://yoursite.com/2020/05/30/%E9%87%8D%E6%9E%84--%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/Chapter%202%20%E9%87%8D%E6%9E%84%E7%9A%84%E5%8E%9F%E5%88%99/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>重构的原则 | 严冰的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="严冰的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">严冰的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/05/30/%E9%87%8D%E6%9E%84--%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/Chapter%202%20%E9%87%8D%E6%9E%84%E7%9A%84%E5%8E%9F%E5%88%99/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/dog.jpg">
      <meta itemprop="name" content="yanbing">
      <meta itemprop="description" content="闲看庭前花开落，漫随天外云卷舒。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="严冰的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          重构的原则
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-05-30 20:50:49" itemprop="dateCreated datePublished" datetime="2020-05-30T20:50:49+08:00">2020-05-30</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-06-18 08:01:07" itemprop="dateModified" datetime="2020-06-18T08:01:07+08:00">2020-06-18</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8D%E6%9E%84-%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/" itemprop="url" rel="index"><span itemprop="name">重构--阅读笔记</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="1-什么是重构？"><a href="#1-什么是重构？" class="headerlink" title="1.什么是重构？"></a>1.什么是重构？</h3><p>在不改变软件可观察行为的前提下，使用一些重构的手法，提高代码可读性。</p>
<p>换句话说，在保持软件可用的前提下，修改代码使得更加容易被理解。</p>
<a id="more"></a>
<h3 id="2-为什么重构？"><a href="#2-为什么重构？" class="headerlink" title="2.为什么重构？"></a>2.为什么重构？</h3><p>为了后续的代码维护和修改，易读是重构的核心价值。</p>
<p>除此之外，重构随之带来的好处有：</p>
<p>找到bug<br>提高编程速度（在代码量累计到一定程度时，重构过的代码会更加易于添加新功能）</p>
<h3 id="3-什么时候重构？"><a href="#3-什么时候重构？" class="headerlink" title="3.什么时候重构？"></a>3.什么时候重构？</h3><ul>
<li>添加新功能之前重构</li>
</ul>
<p>添加新功能最快的方法往往是先修改现有代码，使新功能容易被加入。</p>
<ul>
<li><p>使代码更易理解时重构</p>
</li>
<li><p>顺便重构（修复bug，添加新功能）</p>
</li>
<li><p>代码复审（code review）时重构</p>
</li>
</ul>
<p>总而言之：重构的门槛远远没有想象中那么高，重构是对既有代码的修改，也许我们在无意识中就已经做了这样的工作，一方面继续保持良好的编程习惯，另一方面学习更加成体系的重构手法。</p>
<p>就如同重构的定义，在可用的前提下，提高重构的技术。</p>
<p><strong>什么时候不应该重构？</strong></p>
<p>对于一段凌乱的代码，如果不需要修改它，就不需要重构。</p>
<p>只有当你需要理解其工作原理时，重构才变得有价值。</p>
<p>如果重写比重构更加容易，那就不需要重构了。（判断）</p>
<h3 id="4-重构会遇到哪些问题？"><a href="#4-重构会遇到哪些问题？" class="headerlink" title="4.重构会遇到哪些问题？"></a>4.重构会遇到哪些问题？</h3><p><code>“毕竟生活里很少有晴空万里的好事”       **——Martin Fowler**</code></p>
<ul>
<li>延缓新功能开发</li>
</ul>
<p>先添加新功能再重构，还是先重构再添加新功能，这不是一个对错的问题，而是一个取舍的分叉口。</p>
<p>Martin Fowler的回答醍醐灌顶，作为程序员往往对代码库的整洁有着极高的追求，以技术去驱动重构没有错，但现实世界往往取决于经济。</p>
<p>“重构的意义不在于把代码库打磨的闪闪发光，而是纯粹经济角度出发的考量。”</p>
<p>“重构应该总是由经济利益驱动。”</p>
<p>除了重构之外，现在的团队开发，前后端分离等等，不仅是技术发展的必然结果，同时也是经济化必然的结果。同样的场景，是否重构更多取决于经济条件。</p>
<ul>
<li>代码所有权成为重构阻力</li>
</ul>
<p>修改函数声明和调用可能也会遭遇声明者无法修改调用者代码的权限问题。</p>
<p>Martin Fowler推荐的是团队代码所有制。对于跨团队的兼容，可以采用类似GitHub上开源的模型。</p>
<p>(在强代码所有制和混乱修改的折中)</p>
<ul>
<li>分支合并问题</li>
</ul>
<p>在隔离的分支上工作的越久，需要完成的集成工作就越困难。</p>
<p>持续集成（CI：Continuous Integration）：也称基于主干开发。为了避免彼此分支差异过大，每个团队成员每天至少向主线集成一次。</p>
<p>使用CI的代价：必须使用相关的实践保持主线的健康状态。</p>
<ul>
<li>快速的自测试</li>
</ul>
<p>建立一套完备的测试套件，并且需要快速运行。</p>
<p>准备这套测试套件的代价很高，但收益也是可观的：</p>
<p>使重构可行性变得更大<br>使添加新功能更加安全<br>bug排查更加迅速，容易</p>
<ul>
<li>遗留代码</li>
</ul>
<p>重构可以很好的理解遗留系统，但同时又是十分危险的。</p>
<p>再次推书了，hhh《修改代码的艺术》：运用重构手法创造出接缝，在接缝处插入测试。（当然，具有一定风险）</p>
<ul>
<li>数据库</li>
</ul>
<p>flower先生的同事发明了一套渐进式数据库设计和数据库重构的方法…….</p>
<h3 id="5-重构与性能优化"><a href="#5-重构与性能优化" class="headerlink" title="5.重构与性能优化"></a>5.重构与性能优化</h3><p>重构：使代码更易读</p>
<p>性能优化：使代码运行速度更快</p>
<p>先写出可调优的软件（重构），然后对其调优达到足够的速度（性能优化）。</p>
<p>关于性能优化：现状——大半时间都花在了一小段代码上。</p>
<p>使用一个度量工具监控程序的运行，找出性能热点的一小段代码集中调优。</p>
<h3 id="6"><a href="#6" class="headerlink" title="6"></a>6</h3><p>.自动化重构<br>Intellij IDEA可以自动重构的…</p>

    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>yanbing
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://yoursite.com/2020/05/30/%E9%87%8D%E6%9E%84--%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/Chapter%202%20%E9%87%8D%E6%9E%84%E7%9A%84%E5%8E%9F%E5%88%99/" title="重构的原则">http://yoursite.com/2020/05/30/重构--阅读笔记/Chapter 2 重构的原则/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/05/30/Java%E5%9F%BA%E7%A1%80/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B/" rel="prev" title="Java多线程">
      <i class="fa fa-chevron-left"></i> Java多线程
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/05/30/%E9%87%8D%E6%9E%84--%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/Chapter%203%20%E4%BB%A3%E7%A0%81%E7%9A%84%E5%9D%8F%E5%91%B3%E9%81%93/" rel="next" title="代码的坏味道">
      代码的坏味道 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-什么是重构？"><span class="nav-number">1.</span> <span class="nav-text">1.什么是重构？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-为什么重构？"><span class="nav-number">2.</span> <span class="nav-text">2.为什么重构？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-什么时候重构？"><span class="nav-number">3.</span> <span class="nav-text">3.什么时候重构？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-重构会遇到哪些问题？"><span class="nav-number">4.</span> <span class="nav-text">4.重构会遇到哪些问题？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-重构与性能优化"><span class="nav-number">5.</span> <span class="nav-text">5.重构与性能优化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6"><span class="nav-number">6.</span> <span class="nav-text">6</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="yanbing"
      src="/images/dog.jpg">
  <p class="site-author-name" itemprop="name">yanbing</p>
  <div class="site-description" itemprop="description">闲看庭前花开落，漫随天外云卷舒。</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">59</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/yanbingzn" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;yanbingzn" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/i_silence" title="CSDN → https:&#x2F;&#x2F;blog.csdn.net&#x2F;i_silence" rel="noopener" target="_blank"><i class="fab fa-codiepie fa-fw"></i>CSDN</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="http://www.beian.miit.gov.cn/" rel="noopener" target="_blank">豫ICP备20019377号 </a>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yanbing</span>
</div>

<span id="busuanzi_container_site_uv">
  本站访问次数：<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
</span>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/canvas-ribbon/canvas-ribbon.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













  

  


  
  <script type="text/javascript"
color="0,0,188" opacity='0.5' zIndex="-1" count="120" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  

</body>
</html>
